<template>
  <el-config-provider :locale="zhCn">
    <div>
      <el-form :model="jobTransferForm" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="24">
            <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
              <el-form-item label="岗位调动" label-position="top"
                :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                <div class="progress-bar">
                  <div class="progress"></div>
                </div>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="员工" prop="employeeId" label-position="top" required>
                <div style="display: flex; width: 300px;">
                  <el-input 
                    placeholder="选择员工" 
                    v-model="employeeDisplay" 
                    style="flex: 1;" 
                    readonly
                    @click="openEmployeeDialog">
                    <template #append>
                      <el-button :icon="Search" @click="openEmployeeDialog" />
                    </template>
                  </el-input>
                </div>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="申请日期" prop="applicationDate" label-position="top" required>
                <el-date-picker v-model="jobTransferForm.applicationDate" type="datetime" 
                  placeholder="选择日期时间" format="YYYY/MM/DD HH:mm:ss" style="width: 300px;">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="工号" prop="employeeIdNumber" label-position="top" required>
                <el-input placeholder="输入你的工号" v-model="jobTransferForm.employeeIdNumber" 
                  style="width: 300px;" clearable disabled />
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="姓名" prop="employeeName" label-position="top" required>
                <el-input placeholder="输入你的名字" v-model="jobTransferForm.employeeName" 
                  style="width: 300px;" clearable disabled />
              </el-form-item>
            </div>
          </el-col>
          
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="聘用方式" prop="employmentForm" label-position="top" required>
                <el-select v-model="jobTransferForm.employmentForm" placeholder="选择聘用方式"
                  style="width: 300px" placement="bottom" disabled>
                  <el-option v-for="item in employmentTypeList" :key="item.value"
                    :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="员工状态" prop="employeeStatus" label-position="top" required>
                <el-input placeholder="输入员工状态" v-model="jobTransferForm.employeeStatus" 
                  style="width: 300px" clearable disabled />
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="入职日期" prop="entryDate" label-position="top" required>
                <el-date-picker v-model="jobTransferForm.entryDate" type="datetime" 
                  placeholder="选择日期时间" format="YYYY/MM/DD HH:mm:ss" style="width: 300px;" disabled>
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="经办HR" prop="handlerHr" label-position="top" required>
                <el-input placeholder="输入经办HR" v-model="jobTransferForm.handlerHr" 
                  style="width:300px" clearable />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="24">
            <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
              <el-form-item label="调出信息" label-position="top"
                :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                <div class="progress-bar">
                  <div class="progress"></div>
                </div>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="原岗位" prop="originalPosition" label-position="top" required>
                <el-input placeholder="输入原岗位" clearable style="width:300px" 
                  v-model="jobTransferForm.originalPosition" disabled />
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="原部门" prop="originalDepartment" label-position="top" required>
                <el-input placeholder="输入原部门" clearable style="width: 300px" 
                  v-model="jobTransferForm.originalDepartment" disabled />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="调出部门主管" prop="outSupervisor" label-position="top">
                <el-input placeholder="输入调出部门主管" clearable style="width: 300px" 
                  v-model="jobTransferForm.outSupervisor" />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="调动原因" prop="transferReason" label-position="top" required>
                <el-input placeholder="输入调动原因" clearable style="width:300px" 
                  v-model="jobTransferForm.transferReason" />
              </el-form-item>
            </div>
          </el-col>   
          
          <el-col :span="24">
            <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
              <el-form-item label="调入信息" label-position="top"
                :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                <div class="progress-bar">
                  <div class="progress"></div>
                </div>
              </el-form-item>
            </div>
          </el-col>
          
           <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="调入部门" prop="transferDepartment" label-position="top" required>
                <el-select v-model="jobTransferForm.transferDepartment" placeholder="选择调入部门" 
                  style="width: 300px" placement="bottom">
                  <el-option v-for="item in departmentList" :key="item.deptId" :label="item.deptName"
                    :value="item.deptId" />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="调入岗位" prop="transferPosition" label-position="top" required>
                <el-select v-model="jobTransferForm.transferPosition" placeholder="选择调入岗位" 
                  style="width: 300px" placement="bottom">
                  <el-option v-for="item in postList" :key="item.postId" :label="item.postName"
                    :value="item.postId" />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="调动后薪资" prop="newSalary" label-position="top" required>
                <el-input placeholder="输入调动后薪资" clearable style="width: 300px" 
                  v-model="jobTransferForm.newSalary" />
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="调入部门主管" prop="inSupervisor" label-position="top" required>
                <el-input placeholder="输入调入部门主管" clearable style="width: 300px" 
                  v-model="jobTransferForm.inSupervisor" />
              </el-form-item>
            </div>
          </el-col>

         <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="调入部门主管审批结果" prop="supervisorApproval" label-position="top" required>
                <el-radio-group v-model="jobTransferForm.supervisorApproval">
                  <el-radio label="通过">通过</el-radio>
                  <el-radio label="不通过">不通过</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="24">
            <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
              <el-form-item label="HR确认" label-position="top"
                :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                <div class="progress-bar">
                  <div class="progress"></div>
                </div>
              </el-form-item>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="调动完成时间" prop="completionTime" label-position="top" required>
                <el-date-picker v-model="jobTransferForm.completionTime" type="datetime" 
                  placeholder="选择日期时间" format="YYYY/MM/DD HH:mm:ss" style="width: 300px;">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col>
              
          <el-col :span="12">
            <div class="grid-content ep-bg-purple-light">
              <el-form-item label="HR确认" prop="hrConfirm" label-position="top" required>
                <el-input placeholder="输入HR确认信息" clearable style="width: 300px" 
                  v-model="jobTransferForm.hrConfirm" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        
        <hr>
        <el-form-item style="margin-top: 6px;">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 员工选择对话框 -->
      <el-dialog v-model="employeeDialogVisible" title="选择员工" width="800px">
        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :span="12">
            <el-input 
              v-model="employeeSearchKeyword" 
              placeholder="搜索员工姓名或工号" 
              clearable
              @keyup.enter="searchEmployees">
              <template #append>
                <el-button :icon="Search" @click="searchEmployees" />
              </template>
            </el-input>
          </el-col>
        </el-row>
        
        <el-table 
          :data="employeeList" 
          border 
          style="width: 100%" 
          height="400"
          @row-click="selectEmployee">
          <el-table-column prop="employeeName" label="姓名" width="120" />
          <el-table-column prop="employeeIdNumber" label="工号" width="150" />
          <el-table-column prop="employeeNumber" label="身份证号" width="180" />
          <el-table-column prop="onboardingDepartment" label="部门" width="120" />
          <el-table-column prop="entryPosition" label="岗位" width="120" />
          <el-table-column prop="employmentForm" label="聘用形式" width="120" />
          <el-table-column prop="dateOfInduction" label="入职日期" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.dateOfInduction) }}
            </template>
          </el-table-column>
        </el-table>
        
        <el-pagination 
          v-model:current-page="employeeCurrentPage" 
          v-model:page-size="employeePageSize" 
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper" 
          :total="employeeTotal"
          @size-change="handleEmployeeSizeChange" 
          @current-change="handleEmployeeCurrentChange"
          style="margin-top: 20px; text-align: right;">
        </el-pagination>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="employeeDialogVisible = false">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import server from '@/api/request'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import axios from 'axios'
import { Search } from '@element-plus/icons-vue'

const router = useRouter()
const formRef = ref(null)

// 员工选择相关
const employeeDialogVisible = ref(false)
const employeeDisplay = ref('')
const employeeSearchKeyword = ref('')
const employeeCurrentPage = ref(1)
const employeePageSize = ref(10)
const employeeTotal = ref(0)
const employeeList = ref([])

const jobTransferForm = reactive({
  employeeId: null, 
  employeeIdNumber: '',
  employeeName: '', 
  employmentForm: '',
  employeeStatus: '',
  entryDate: '',
  handlerHr: '',
  originalPosition: '',
  originalDepartment: '',
  outSupervisor: '',
  transferReason: '',
  transferDepartment: null,
  transferPosition: null,
  newSalary: '',
  inSupervisor: '',
  supervisorApproval: '通过',
  completionTime: '',
  hrConfirm: '',
  applicationDate: ''
})

// 表单验证规则
const rules = {
  employeeId: [{ required: true, message: '请选择员工', trigger: 'change' }],
  applicationDate: [{ required: true, message: '请选择申请日期', trigger: 'change' }],
  employeeIdNumber: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
  employeeName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  employmentForm: [{ required: true, message: '请选择聘用方式', trigger: 'change' }],
  employeeStatus: [{ required: true, message: '员工状态不能为空', trigger: 'blur' }],
  entryDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }],
  handlerHr: [{ required: true, message: '请输入经办HR', trigger: 'blur' }],
  originalPosition: [{ required: true, message: '原岗位不能为空', trigger: 'blur' }],
  originalDepartment: [{ required: true, message: '原部门不能为空', trigger: 'blur' }],
  transferReason: [{ required: true, message: '请输入调动原因', trigger: 'blur' }],
  transferDepartment: [{ required: true, message: '请选择调入部门', trigger: 'change' }],
  transferPosition: [{ required: true, message: '请选择调入岗位', trigger: 'change' }],
  newSalary: [{ required: true, message: '请输入调动后薪资', trigger: 'blur' }],
  inSupervisor: [{ required: true, message: '请输入调入部门主管', trigger: 'blur' }],
  supervisorApproval: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
  completionTime: [{ required: true, message: '请选择调动完成时间', trigger: 'change' }],
  hrConfirm: [{ required: true, message: '请输入HR确认信息', trigger: 'blur' }]
}

const departmentList = ref([])
const postList = ref([])
const employmentTypeList = ref([
  { value: '实习', label: '实习' },
  { value: '兼职', label: '兼职' },
  { value: '全职', label: '全职' }
])

// 打开员工选择对话框
const openEmployeeDialog = async () => {
  employeeDialogVisible.value = true
  await fetchEmployees()
}

// 获取员工列表
const fetchEmployees = async () => {
  try {
    const response = await server.get('/into/findPage', {
      params: {
        pageNum: employeeCurrentPage.value,
        pageSize: employeePageSize.value,
        keyword: employeeSearchKeyword.value
      }
    })
    
    if (response.code === 200) {
      employeeList.value = response.data.records
      employeeTotal.value = response.data.total
    } else {
      ElMessage.error('获取员工列表失败: ' + response.message)
    }
  } catch (error) {
    ElMessage.error('获取员工列表失败: ' + (error.message || '未知错误'))
  }
}

// 搜索员工
const searchEmployees = () => {
  employeeCurrentPage.value = 1
  fetchEmployees()
}
// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 检查是否选择了员工
        if (!jobTransferForm.employeeId) {
          ElMessage.error('请先选择员工')
          return
        }
        
        // 构造完整的提交数据，确保所有必填字段都有值
        const submitData = {
          employeeId: jobTransferForm.employeeId,
          employeeIdNumber: jobTransferForm.employeeIdNumber || '',
          employeeName: jobTransferForm.employeeName || '',
          employmentForm: jobTransferForm.employmentForm || '',
          employeeStatus: jobTransferForm.employeeStatus || '',
          entryDate: jobTransferForm.entryDate || null,
          handlerHr: jobTransferForm.handlerHr || '',
          originalPosition: jobTransferForm.originalPosition || '',
          originalDepartment: jobTransferForm.originalDepartment || '',
          outSupervisor: jobTransferForm.outSupervisor || '',
          transferReason: jobTransferForm.transferReason || '',
          transferDepartment: jobTransferForm.transferDepartment,
          transferPosition: jobTransferForm.transferPosition,
          newSalary: jobTransferForm.newSalary || '',
          inSupervisor: jobTransferForm.inSupervisor || '',
          supervisorApproval: jobTransferForm.supervisorApproval || '通过',
          completionTime: jobTransferForm.completionTime || null,
          hrConfirm: jobTransferForm.hrConfirm || '',
          applicationDate: jobTransferForm.applicationDate || null,
          submitTime: new Date(),
          updateTime: new Date()
        }
        
        const response = await server.post('/jobtransfer/add', submitData)
        
        if (response.code === 200) {
          ElMessage.success('添加成功')
          goBack()
        } else {
          ElMessage.error('添加失败: ' + response.message)
        }
      } catch (error) {
        console.error('添加失败:', error)
        ElMessage.error('添加失败: ' + (error.message || '网络错误'))
      }
    }
  })
}
// 选择员工
const selectEmployee = (row) => {
  jobTransferForm.employeeId = row.employeeId
  jobTransferForm.employeeIdNumber = row.employeeIdNumber || ''
  jobTransferForm.employeeName = row.employeeName || ''
  jobTransferForm.employmentForm = row.employmentForm || ''
  jobTransferForm.employeeStatus = row.employeeStatus || ''
  jobTransferForm.entryDate = row.dateOfInduction || null
  jobTransferForm.originalPosition = row.entryPosition || ''
  jobTransferForm.originalDepartment = row.onboardingDepartment || ''
  jobTransferForm.handlerHr = row.responsibleFoHr || row.responsible_fo_hr || ''
  
  employeeDisplay.value = `${row.employeeName} (${row.employeeIdNumber})`
  employeeDialogVisible.value = false
}
// 处理员工分页大小变化
const handleEmployeeSizeChange = (val) => {
  employeePageSize.value = val
  fetchEmployees()
}

// 处理员工当前页变化
const handleEmployeeCurrentChange = (val) => {
  employeeCurrentPage.value = val
  fetchEmployees()
}

// 获取岗位列表
const fetchPosts = async () => {
  try {
    // 修改为正确的后端接口路径
    const response = await server.get('/system/permission/post/find')
    if (response.code === 200) {
      postList.value = response.data.map(item => ({
        postId: item.postId,
        postName: item.postName
      }))
    } else {

      ElMessage.warning('岗位数据获取失败，使用默认数据')
    }
  } catch (error) {

    ElMessage.warning('岗位数据获取失败，使用默认数据: ' + error.message)
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  try {

    const response = await server.get('/department/find')
    if (response.code === 200) {
      departmentList.value = response.data.map(item => ({
        deptId: item.deptId,
        deptName: item.deptName
      }))
    } else {

      ElMessage.warning('部门数据获取失败，使用默认数据')
    }
  } catch (error) {

    ElMessage.warning('部门数据获取失败，使用默认数据: ' + error.message)
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  employeeDisplay.value = ''
  // 重置表单数据
  Object.keys(jobTransferForm).forEach(key => {
    jobTransferForm[key] = ''
  })
  jobTransferForm.supervisorApproval = '通过'
  jobTransferForm.employeeId = null
  jobTransferForm.transferDepartment = null
  jobTransferForm.transferPosition = null
}

// 返回上一页
const goBack = () => {
  router.back()
}


onMounted(() => {
  fetchEmployees()
  fetchDepartments()
  fetchPosts()
})
</script>

<style scoped>
.progress-bar {
  height: 6px;
  background-color: #ccebf7;
  border-radius: 3px;
  display: flex;
  width: 100%;
  overflow: hidden;
}

.progress {
  width: 8%;
  height: 10;
  background-color: #61c3ea;
  border-radius: 3px 0 0 3px;
  transition: width 0.3s ease;
}

.el-radio.is-checked .radio-custom {
  background-color: #61c3ea;
  border-color: #409EFF;
}
</style>